package com.lag.transfer.dao.impl;

import com.lag.transfer.annotation.MyDefinedAutowired;
import com.lag.transfer.annotation.MyDefinedRepository;
import com.lag.transfer.dao.AccountDao;
import com.lag.transfer.pojo.Account;
import com.lag.transfer.utils.ConnectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用声明式事务对dao层进行重写
 *
 * @author June
 * @since 2020年12月
 */
@MyDefinedRepository("accountDao")
public class JdbcTemplateDaoImpl implements AccountDao {

    // @Autowired
    // private JdbcTemplate jdbcTemplate;

    @MyDefinedAutowired("connectionUtils")
    private ConnectionUtils connectionUtils;

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        String sql = "select * from account where cardNo=?";
        /*return jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account account = new Account();
                account.setName(resultSet.getString("name"));
                account.setCardNo(resultSet.getString("cardNo"));
                account.setMoney(resultSet.getInt("money"));
                return account;
            }
        }, cardNo);*/

        Connection con = connectionUtils.getCurrThreadConnection();
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while(resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();
        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
        String sql = "update account set money=? where cardNo=?";
        // return jdbcTemplate.update(sql, account.getMoney(), account.getCardNo());

        Connection con = connectionUtils.getCurrThreadConnection();
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
        return i;
    }
}
